from settings import *
import pygame

class Board(object):
    def __init__(self):
        self.status = []
        for i in range(8):
            l = list()
            for i in range(8):
                l.append(0)
            self.status.append(l)

        self.status[3][3] = 2
        self.status[3][4] = 1
        self.status[4][3] = 1
        self.status[4][4] = 2

        self.round = 2

    def is_valid(self, row, line):
        ls = [-1, -1, 0, 1, 1, 1, 0, -1]
        rs = [0,  -1, -1, -1, 0, 1, 1, 1]

        for k in range(8):
            if (self.can_reverse(row, line, ls[k], rs[k])):
                return True

        return False

    def click(self, pos):
        x = pos[0]
        y = pos[1]

        i = (y - PADDING) // GRID_HEIGHT
        j = (x - PADDING) // GRID_WIDTH

        if (self.status[i][j] != 0):
            return

        if (not self.is_valid(i, j)):
            return

        self.status[i][j] = self.round
        self.reverse_all(i, j)
        self.round = 3 - self.round

    def reverse_all(self, row, line):
        ls = [-1, -1, 0, 1, 1, 1, 0, -1]
        rs = [0,  -1, -1, -1, 0, 1, 1, 1]

        for k in range(8):
            if (self.can_reverse(row, line, ls[k], rs[k])):
                self.reverse(row, line, ls[k], rs[k])

    def can_reverse(self, row, line, dir_line, dir_row):
        y = row + dir_row
        x = line + dir_line

        if (y < 0 or y > 7 or x < 0 or x > 7):
            return False

        while (self.status[y][x] == 3 - self.round):
            y += dir_row
            x += dir_line

            if (y < 0 or y > 7 or x < 0 or x > 7):
                return False

            if (self.status[y][x] == 0):
                return False

            if (self.status[y][x] == self.round):
                return True

        return False
            
    def reverse(self, row, line, dir_line, dir_row):
        y = row + dir_row
        x = line + dir_line
        while (self.status[y][x] != self.round):
            self.status[y][x] = self.round
            y += dir_row
            x += dir_line

    def draw(self, screen):
        for i in range(8):
            for j in range(8):
                chess = self.status[i][j]
                x = PADDING + j * GRID_WIDTH + GRID_WIDTH // 2
                y = PADDING + i * GRID_HEIGHT + GRID_HEIGHT // 2
                if chess == 0:
                    continue
                elif chess == 1:
                    pygame.draw.circle(screen, (255, 255, 255), (x, y),
                        GRID_WIDTH // 2 - 5)
                elif chess == 2:
                    pygame.draw.circle(screen, (0, 0, 0), (x, y),
                        GRID_WIDTH // 2 - 5)
        pygame.display.update()

